package com.unionftech.content_login.ui.forget

import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import com.unionftech.common.R.*
import com.unionftech.common.base.mvp.annitation.InjectPresenter
import com.unionftech.common.base.mvp.impl.BaseMvpFragment
import com.unionftech.common.bean.ApiException
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.bean.toast
import com.unionftech.common.bean.toastTimeout
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.RegexUtils
import com.unionftech.common.utils.ToastUtils
import com.unionftech.common.utils.autoSize
import com.unionftech.common.utils.countDown
import com.unionftech.content_login.R
import com.unionftech.content_login.bean.request.ForgetPasswordRequest
import com.unionftech.common.common.bean.request.SendCodeRequest
import com.unionftech.common.common.contract.CommonContract
import com.unionftech.common.common.presenter.CommonPresenter
import com.unionftech.common.utils.CheckInputUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel

class ForgetPasswordCommonFragment : BaseMvpFragment(), CommonContract.ISendCodeView {
    private val mEtVerificationCode: EditText by lazy { mRootView.findViewById(R.id.et_verification_code) }
    private val mIvClearVerifyCode: ImageView by lazy { mRootView.findViewById(R.id.iv_clear_verify_code) }
    private val mTvSendCode: TextView by lazy { mRootView.findViewById(R.id.tv_send_code) }
    private val mTvCodeError: TextView by lazy { mRootView.findViewById(R.id.tv_code_error) }
    private val mEtPassword: EditText by lazy { mRootView.findViewById(R.id.et_password) }
    private val mIvClearPassword: ImageView by lazy { mRootView.findViewById(R.id.iv_clear_password) }
    private val mIvShowPassword: ImageView by lazy { mRootView.findViewById(R.id.iv_show_password) }
    private val mTvPasswordError: TextView by lazy { mRootView.findViewById(R.id.tv_password_error) }
    private val mBtnConfirm: Button by lazy { mRootView.findViewById(R.id.btn_confirm) }
    private var mCompleteListener: ((result: Boolean) -> Unit)? = null
    private var mCountDown: CoroutineScope? = null
    private var mGetParentValueListener: (() -> SendCodeRequest?)? = null
    private var mType = TYPE_REGISTER_EMAIL
    private var mInputChangeCallBack: (() -> Unit)? = null

    @InjectPresenter
    private lateinit var mCommonPresenter: CommonPresenter

    companion object {
        private const val TAG = "ForgetPasswordCommonFragment"
        private const val PARAMS_REGISTER_TYPE = "params_register_type"
        const val TYPE_REGISTER_EMAIL = 1
        const val TYPE_REGISTER_PHONE = 2

        @JvmStatic
        fun newInstance(type: Int) =
            ForgetPasswordCommonFragment().apply {
                arguments = Bundle().apply {
                    putInt(PARAMS_REGISTER_TYPE, type)
                }
            }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }

    override fun obtainIntentData(bundle: Bundle) {
        super.obtainIntentData(bundle)
        mType = bundle.getInt(
            PARAMS_REGISTER_TYPE,
            TYPE_REGISTER_EMAIL
        )
    }

    override fun inflaterContentView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(
            R.layout.fragment_forget_password_common,
            container,
            false
        )
    }

    fun setCompleteListener(listener: (result: Boolean) -> Unit) {
        mCompleteListener = listener
    }

    override fun initLanguageText() {
        super.initLanguageText()
        mEtVerificationCode.hint =
            DynamicResourceManager.getString(mContext, string.verification_code)
        mTvSendCode.text = DynamicResourceManager.getString(mContext, string.send_OTP)
        mEtPassword.hint = DynamicResourceManager.getString(mContext, string.password_hint)
        mBtnConfirm.text = DynamicResourceManager.getString(mContext, string.confirm)
    }

    override fun setListener() {
        super.setListener()
        mIvShowPassword.setOnClickListener(this)
        mTvSendCode.setOnClickListener(this)
        mBtnConfirm.setOnClickListener(this)
        mIvClearPassword.setOnClickListener(this)
        addTextChangeListener(mEtPassword, mIvClearPassword)
        addFocusChangeListener(mEtPassword, mIvClearPassword)
        mIvClearVerifyCode.setOnClickListener(this)
        addTextChangeListener(mEtVerificationCode, mIvClearVerifyCode)
        addFocusChangeListener(mEtVerificationCode, mIvClearVerifyCode)
    }

    override fun setView() {
        super.setView()
        hideTitleBar()
        mRootView.setBackgroundColor(mContext.getColor(android.R.color.transparent))
        mTvPasswordError.autoSize(
            mContext.resources.getDimension(dimen.sp_8).toInt(),
            mContext.resources.getDimension(dimen.sp_10).toInt()
        )
    }

    fun setGetParentValueListener(listener: () -> SendCodeRequest?) {
        mGetParentValueListener = listener
    }

    private fun addTextChangeListener(editText: EditText, clearView: ImageView? = null) {
        editText.addTextChangedListener { text ->
            setClearView(text, clearView)
            mInputChangeCallBack?.invoke()
        }
    }

    private fun addFocusChangeListener(
        editText: EditText,
        clearView: ImageView? = null
    ) {
        editText.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                //去除错误边框展示
                editText.isSelected = false
                setClearView(editText.text, clearView)
            } else {
                clearView?.visibility = View.GONE
                checkInput(editText)
            }
        }
    }

    private fun setClearView(text: Editable?, clearView: ImageView?) {
        if (!TextUtils.isEmpty(text)) {
            clearView?.visibility = View.VISIBLE
        } else {
            clearView?.visibility = View.GONE
        }
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.iv_clear_password -> mEtPassword.setText("")
            R.id.tv_send_code -> sendCode()
            R.id.iv_clear_verify_code -> mEtVerificationCode.setText("")
            R.id.iv_show_password -> {
                if (mIvShowPassword.isSelected) {
                    hidePasswordText()
                } else {
                    showPasswordText()
                }
            }

            R.id.btn_confirm -> {
                mEtPassword.clearFocus()
                mEtVerificationCode.clearFocus()
                mCompleteListener?.invoke(checkInput())
            }
        }
    }

    private fun sendCode() {
        val requestBean = mGetParentValueListener?.invoke()
        requestBean?.also { bean ->
            if (mType == TYPE_REGISTER_EMAIL) {
                if (TextUtils.isEmpty(bean.loginEmail)) {
                    return
                }
            } else if (mType == TYPE_REGISTER_PHONE) {
                if (TextUtils.isEmpty(bean.loginPhone)
                    || TextUtils.isEmpty(bean.areaCode)
                    || TextUtils.isEmpty(bean.areaCountry)
                ) {
                    return
                }
            }
            sendCode(requestBean)
        }
    }

    private fun sendCode(request: SendCodeRequest) {
        mCommonPresenter.execSendCode(request)
    }

    private fun startCountDown() {
        val resendText = DynamicResourceManager.getString(mContext, string.resend)
        mActivity.countDown(time = 60,
            start = {
                mCountDown = it
                mTvSendCode.isEnabled = false
            }, end = {
                mTvSendCode.text = resendText
                mTvSendCode.isEnabled = true
            }, next = {
                mTvSendCode.text = "${it}s"
            }, error = {
                mTvSendCode.isEnabled = true
            })
    }

    private fun checkInput(): Boolean {
        return CheckInputUtil.checkInput(
            mEtVerificationCode.text.toString(),
            RegexUtils.VERIFYCODE_REGEX,
            mEtVerificationCode,
            mTvCodeError,
            string.verification_code_empty,
            string.verification_code_incorrect
        ) and CheckInputUtil.checkInput(
            mEtPassword.text.toString(),
            RegexUtils.PASSWORD_REGEX,
            mEtPassword,
            mTvPasswordError,
            string.password_empty,
            string.password_incorrect
        )
    }

    private fun checkInput(editText: EditText) {
        when (editText) {
            mEtPassword -> CheckInputUtil.checkInput(
                mEtPassword.text.toString(),
                RegexUtils.PASSWORD_REGEX,
                mEtPassword,
                mTvPasswordError,
                string.password_empty,
                string.password_incorrect
            )

            mEtVerificationCode -> CheckInputUtil.checkInput(
                mEtVerificationCode.text.toString(),
                RegexUtils.VERIFYCODE_REGEX,
                mEtVerificationCode,
                mTvCodeError,
                string.verification_code_empty,
                string.verification_code_incorrect
            )
        }
    }

    private fun hidePasswordText() {
        mIvShowPassword.isSelected = false
        mIvShowPassword.setImageResource(drawable.icon_eye_off)
        mEtPassword.transformationMethod = PasswordTransformationMethod.getInstance()
        mEtPassword.setSelection(mEtPassword.text.length)
    }

    private fun showPasswordText() {
        mIvShowPassword.isSelected = true
        mIvShowPassword.setImageResource(drawable.icon_eye_on)
        mEtPassword.transformationMethod = HideReturnsTransformationMethod.getInstance()
        mEtPassword.setSelection(mEtPassword.text.length)
    }


    fun getResetRequestInfo(): ForgetPasswordRequest {
        return ForgetPasswordRequest(
            encryptPassword = mEtPassword.text.toString(),
            verifyCode = mEtVerificationCode.text.toString()
        )
    }

    fun setInputChangeCallBack(callBack: () -> Unit) {
        this.mInputChangeCallBack = callBack
    }

    fun getInputEnable(): Boolean {
        return !TextUtils.isEmpty(mEtPassword.text)
                && !TextUtils.isEmpty(mEtVerificationCode.text)
    }

    fun setConfirmEnable(enable: Boolean) {
        mBtnConfirm.isEnabled = enable
    }

    fun resetData() {
        mEtPassword.setText("")
        hidePasswordText()
        mEtVerificationCode.setText("")
        mCountDown?.cancel()
        mBtnConfirm.isEnabled = false
    }

    override fun handleSendCode(response: ResponseResult<Any?>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            startCountDown()
            ToastUtils.longToast(
                DynamicResourceManager.getString(
                    mContext,
                    string.send_code_success
                )
            )
        } else {
            LogUtils.e(TAG, "handleSendCode error code: ${response.code} msg: ${response.msg}")
            if (ApiException.isTimeout(response.code)) {
                response.toastTimeout()
            } else {
                response.toast()
            }
        }
    }

    override fun onDestroy() {
        mCountDown?.cancel()
        super.onDestroy()
    }

}